package store

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"time"
)

type Redis struct {
	conf *Config
}

func (s *Redis) Get() *redis.Client {
	redisOnce.Do(func() {
		redisClient = redis.NewClient(&redis.Options{
			Addr:     "127.0.0.1:6379",
			Password: "Justin.Hu!#$_2021",
			DB:       0,
		})
	})
	return redisClient
}

func (s *Redis) GetSendEmailKey(email, from string) string {
	return fmt.Sprintf("class:email_%s:%s", from, email)
}

func (s *Redis) Publish(name string, data interface{}) (err error) {
	body, e := json.Marshal(data)
	if e != nil {
		err = e
		return
	}
	client := s.Get()
	err = client.LPush(name, body).Err()
	return
}

func (s *Redis) Consume(name string, cb func(bs []byte)) (err error) {
	client := s.Get()
	for {
		data, err := client.BRPop(time.Second*3, name).Result()
		if err != nil {
			continue
		}
		cb([]byte(data[1]))
	}
	return
}
